package cn.tedu.management.portal.service.impl;

import cn.tedu.management.portal.dto.PostAddRoleDTO;
import cn.tedu.management.portal.ex.DeleteException;
import cn.tedu.management.portal.ex.InsertException;
import cn.tedu.management.portal.ex.NotFoundException;
import cn.tedu.management.portal.mapper.RoleMapper;
import cn.tedu.management.portal.mapper.StaffMapper;
import cn.tedu.management.portal.mapper.StaffRoleMapper;
import cn.tedu.management.portal.model.Role;
import cn.tedu.management.portal.model.Staff;
import cn.tedu.management.portal.model.StaffRole;
import cn.tedu.management.portal.service.IRoleService;
import cn.tedu.management.portal.vo.RoleVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-12-08
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    StaffMapper staffMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    StaffRoleMapper staffRoleMapper;

    @Override
    @Transactional
    public void registerUser(PostAddRoleDTO postAddRoleDTO) {
        LocalDateTime now = LocalDateTime.now();
        Role role = new Role();
        role.setName(postAddRoleDTO.getName());
        role.setGmtCreate(now);
        role.setGmtModified(now);
        int rows = roleMapper.insert(role);
        if (rows != 1) {
            throw new InsertException("添加失败,稍后重试");
        }
        RoleVo roleVo = roleMapper.findById(postAddRoleDTO.getPhone());
        String str = ""+roleVo;
        String str1= str.substring(10,str.length()-1);
        int str2 = Integer.parseInt(str1);
        StaffRole staffRole = new StaffRole();
        staffRole.setStaffId(str2);
        staffRole.setRoleId(role.getId());
        staffRole.setGmtCreate(now);
        staffRole.setGmtModified(now);
        rows = staffRoleMapper.insert(staffRole);
        if (rows != 1) {
            throw new InsertException("添加失败,稍后重试");
        }

    }

    @Override
    public void deleteById(Integer id) {
       Role role = roleMapper.selectById(id);
       if (role == null){
           throw new NotFoundException("不存在");
       }
       int row = roleMapper.deleteById(id);
       if (row != 1){
           throw new DeleteException("删除失败");
       }
    }

}




